package com.corpgovernment.organization.service.budget;

import com.corpgovernment.api.ordercenter.dto.budget.OrderBudgetRequestDto;
import com.corpgovernment.api.ordercenter.dto.budget.QueryOrderDetailResponse;
import com.corpgovernment.api.organization.soa.resident.GenBudgetRequestBO;
import com.corpgovernment.api.platform.soa.response.GetMbBudgetInfoResponse;
import com.corpgovernment.api.platform.soa.response.GetOrderBillDateResponse;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.enums.OrderTypeEnum;
import com.corpgovernment.common.utils.DateUtil;
import com.corpgovernment.common.utils.LogSplicingUtils;
import com.corpgovernment.organization.dataloader.OrderClientLoader;
import com.corpgovernment.organization.dataloader.PpPaymentBillClientLoader;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.budget.BudgetInfoEntity;
import com.corpgovernment.organization.entity.db.budget.BudgetItemEntity;
import com.corpgovernment.organization.entity.db.budget.BudgetNotifyEntity;
import com.corpgovernment.organization.entity.db.budget.BudgetWarningEntity;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.enumm.budget.BudgetScopeEnum;
import com.corpgovernment.organization.enumm.budget.BudgetTypeEnum;
import com.corpgovernment.organization.mapper.MbOrgInfoMapper;
import com.corpgovernment.organization.mapper.budget.BudgetInfoMapper;
import com.corpgovernment.organization.mapper.budget.BudgetItemMapper;
import com.corpgovernment.organization.mapper.budget.BudgetNotifyMapper;
import com.corpgovernment.organization.mapper.budget.BudgetWarningMapper;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ks.Xing
 * <p>
 * description:
 * create: 2023-03-21 13:15
 */
@Slf4j
@Service
public class BudgetStatisticsService {
    @Autowired
    private SearchBudgetService searchBudgetService;
    @Autowired
    private PpPaymentBillClientLoader ppPaymentBillClientLoaderl;
    @Autowired
    private OrderClientLoader orderClientLoader;
    @Autowired
    private BudgetInfoMapper budgetInfoMapper;

    @Autowired
    private BudgetItemMapper budgetItemMapper;

    @Autowired
    private MbOrgInfoMapper mbOrgInfoMapper;
    @Autowired
    private BudgetWarningMapper budgetWarningMapper;
    @Autowired
    private BudgetNotifyMapper budgetNotifyMapper;

    private final static Map<String, String> orderMap = new HashMap(){{
        put("intlhotel","海外酒店");
        put("train","火车");
        put("intlflight","国际机票");
        put("flight","国内机票");
        put("car","打车");
        put("hotel","国内酒店");
    }};



    public JSONResult<Object> count(GenBudgetRequestBO requestVo) {
        StringBuilder logContext = new StringBuilder();
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoMapper.listAll().stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, item -> item, (o1, o2) -> o1));
        try {
            //1 获取当前时间配置的预算配置来进行预算计算
            List<GetMbBudgetInfoResponse> mbBudgetInfoResponses = searchBudgetService.getMbBudgetInfoResponses();
            LogSplicingUtils.addLogContext(logContext, "获取到当前生效的预算配置 %s", JsonUtils.toJsonString(mbBudgetInfoResponses));

            requestVo.setBeginTime(Optional.ofNullable(requestVo.getBeginTime()).orElse(DateUtil.stringToDate(DateUtil.getAddDaysYMD(-1), DateUtil.DF_YMD)));
            requestVo.setEndTime(Optional.ofNullable(requestVo.getEndTime()).orElse(DateUtil.stringToDate(DateUtil.getAddDaysYMD(0), DateUtil.DF_YMD)));

            //2 获取到当前时间段内 支付 && 退款的 订单
            List<GetOrderBillDateResponse> orderBillData = ppPaymentBillClientLoaderl.getOrderBillData(Boolean.FALSE, Collections.emptyList(), null, requestVo.getBeginTime(), requestVo.getEndTime());
            LogSplicingUtils.addLogContext(logContext, "获取到当前时间的支付数据 %s", JsonUtils.toJsonString(orderBillData));
            if (CollectionUtils.isEmpty(mbBudgetInfoResponses) || CollectionUtils.isEmpty(orderBillData)) {
                LogSplicingUtils.addLogContext(logContext, "中断原因 %s", CollectionUtils.isEmpty(mbBudgetInfoResponses) ? "预算配置为空" : "该时间段内无支付数据");
            }

            //3.区分获取到的支付数据非配产线 产线根据订单来区分预算扣款
            Map<String, List<GetOrderBillDateResponse>> orderTypeMap = orderBillData.stream().collect(Collectors.groupingBy(GetOrderBillDateResponse::getOrderType));
            Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap = mbBudgetInfoResponses.stream().collect(Collectors.groupingBy(GetMbBudgetInfoResponse::getCorpId));

            //国内机票
            {
                List<GetOrderBillDateResponse> flightBillDateResponses = orderTypeMap.get(OrderTypeEnum.FN.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的机票数据 %s", JsonUtils.toJsonString(flightBillDateResponses));
                if (CollectionUtils.isNotEmpty(flightBillDateResponses)) {
                    calculateFlightBubgetAmount(flightBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }

            //国际机票
            {
                List<GetOrderBillDateResponse> intlFlightBillDateResponses = orderTypeMap.get(OrderTypeEnum.FI.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的国际机票数据 %s", JsonUtils.toJsonString(intlFlightBillDateResponses));
                if (CollectionUtils.isNotEmpty(intlFlightBillDateResponses)) {
                    calculateIntlFlightBubgetAmount(intlFlightBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }

            //国内酒店
            {
                List<GetOrderBillDateResponse> hotelBillDateResponses = orderTypeMap.get(OrderTypeEnum.HN.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的酒店数据 %s", JsonUtils.toJsonString(hotelBillDateResponses));
                if (CollectionUtils.isNotEmpty(hotelBillDateResponses)) {
                    calculateHotelBubgetAmount(hotelBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }

            //海外酒店
            {
                List<GetOrderBillDateResponse> iHotelBillDateResponses = orderTypeMap.get(OrderTypeEnum.HI.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的国际酒店数据 %s", JsonUtils.toJsonString(iHotelBillDateResponses));
                if (CollectionUtils.isNotEmpty(iHotelBillDateResponses)) {
                    calculateiHotelBubgetAmount(iHotelBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }

            //火车
            {
                List<GetOrderBillDateResponse> trainBillDateResponses = orderTypeMap.get(OrderTypeEnum.TN.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的火车数据 %s", JsonUtils.toJsonString(trainBillDateResponses));
                if (CollectionUtils.isNotEmpty(trainBillDateResponses)) {
                    calculateTrainBubgetAmount(trainBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }

            //打车
            {
                List<GetOrderBillDateResponse> carBillDateResponses = orderTypeMap.get(OrderTypeEnum.CN.getType());
                LogSplicingUtils.addLogContext(logContext, "获取到的打车数据 %s", JsonUtils.toJsonString(carBillDateResponses));
                if (CollectionUtils.isNotEmpty(carBillDateResponses)) {
                    calculateiHotelBubgetAmount(carBillDateResponses, corpBudgetInfoMap, requestVo, orgInfoMap);
                }
            }
        } finally {
            log.info("count--response:{}", logContext);
        }
        //发送预警邮件
        {
            sendWarningMsg(orgInfoMap);
        }
        return JSONResult.ok();
    }

    private void sendWarningMsg(Map<String, MbOrgInfo> orgInfoMap) {
        List<GetMbBudgetInfoResponse> mbBudgetInfoResponses = searchBudgetService.getMbBudgetInfoResponses();

        mbBudgetInfoResponses.stream().forEach(budgetInfoData -> {
            BudgetInfoEntity budgetInfoEntity = budgetInfoMapper.selectByPrimaryKey(budgetInfoData.getId());
            List<BudgetNotifyEntity> budgetNotifyEntities = budgetNotifyMapper.selectByBudgetId(budgetInfoData.getId());
            BigDecimal warningAmount = budgetInfoEntity.getAmount().multiply(budgetInfoEntity.getWarn().divide(new BigDecimal("100")));
            if (budgetInfoEntity.getAmount().subtract(budgetInfoEntity.getAmountUsed()).compareTo(warningAmount) <= 0) {

                String contet = getContet("all", orgInfoMap.get(budgetInfoData.getCorpId()).getName(), DateUtil.dateToString(budgetInfoEntity.getStartTime(), DateUtil.DF_YM_CN)
                        , DateUtil.dateToString(budgetInfoEntity.getEndTime(), DateUtil.DF_YM_CN), budgetInfoEntity.getAmount().toString()
                        , budgetInfoEntity.getAmount().subtract(budgetInfoEntity.getAmountUsed()).toString(), budgetInfoEntity.getWarn().toString() + "%");

                BudgetWarningEntity query = new BudgetWarningEntity();
                query.setBudgetId(budgetInfoEntity.getBudgetId());
                query.setBudgetType("all");
                List<BudgetWarningEntity> select = budgetWarningMapper.select(query);
                if (select.size() > 0) {
                    BudgetWarningEntity update = select.get(0);
                    update.setId(select.get(0).getId());
                    update.setContent(contet);
                    update.setDatachangeLasttime(new Date());
                    budgetWarningMapper.updateByPrimaryKey(update);
                } else {
                    BudgetWarningEntity entity = new BudgetWarningEntity();
                    entity.setBudgetId(budgetInfoEntity.getBudgetId());
                    entity.setBudgetType("all");
                    entity.setContent(contet);
                    entity.setEmall(budgetNotifyEntities.stream().map(BudgetNotifyEntity::getEmail).collect(Collectors.joining(",")));
                    entity.setDatachangeCreatetime(new Date());
                    entity.setDatachangeLasttime(new Date());
                    entity.setIsDeleted(0);
                    budgetWarningMapper.insert(entity);
                }
            }

            List<BudgetItemEntity> budgetItemEntities = budgetItemMapper.selectByBudgetId(budgetInfoData.getId());
            budgetItemEntities.stream().forEach(item -> {
                if (item.getWarn().compareTo(BigDecimal.ZERO) != 0 && !item.getIsAll()) {
                    BigDecimal itemWarningAmount = item.getAmount().multiply(item.getWarn().divide(new BigDecimal("100")));
                    if (item.getAmount().subtract(item.getAmountUsed()).compareTo(itemWarningAmount) <= 0) {
                        Arrays.stream(item.getType().split("/")).forEach(type -> {
                            String contet = getContet("sub", orgInfoMap.get(budgetInfoData.getCorpId()).getName(), DateUtil.dateToString(budgetInfoEntity.getStartTime(), DateUtil.DF_YM_CN)
                                    , DateUtil.dateToString(budgetInfoEntity.getEndTime(), DateUtil.DF_YM_CN), orderMap.get(type), item.getAmount().toString()
                                    , item.getAmount().subtract(item.getAmountUsed()).toString(), item.getWarn().toString() + "%");


                            BudgetWarningEntity query = new BudgetWarningEntity();
                            query.setBudgetId(budgetInfoEntity.getBudgetId());
                            query.setBudgetType("sub");
                            query.setOrderType(type);
                            List<BudgetWarningEntity> select = budgetWarningMapper.select(query);
                            if (select.size() > 0) {
                                BudgetWarningEntity update = select.get(0);
                                update.setId(select.get(0).getId());
                                update.setContent(contet);
                                update.setDatachangeLasttime(new Date());
                                budgetWarningMapper.updateByPrimaryKey(update);
                            } else {
                                BudgetWarningEntity entity = new BudgetWarningEntity();
                                entity.setBudgetId(item.getBudgetId());
                                entity.setBudgetType("sub");
                                entity.setContent(contet);
                                entity.setEmall(budgetNotifyEntities.stream().map(BudgetNotifyEntity::getEmail).collect(Collectors.joining(",")));
                                entity.setOrderType(type);
                                entity.setDatachangeCreatetime(new Date());
                                entity.setDatachangeLasttime(new Date());
                                entity.setIsDeleted(0);
                                budgetWarningMapper.insert(entity);
                            }
                        });
                    }
                }

            });

        });
    }

    private void calculateTrainBubgetAmount(List<GetOrderBillDateResponse> trainBillDateResponses, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, GenBudgetRequestBO requestVo, Map<String, MbOrgInfo> orgInfoMap) {
        List<OrderBudgetRequestDto.OrderInfo> orderIds = trainBillDateResponses.stream().map(response -> {
            return new OrderBudgetRequestDto.OrderInfo(response.getOrderId(), response.getRebookId(), response.getRefundId(), response.getAmount());
        }).collect(Collectors.toList());
        OrderBudgetRequestDto requestDto = new OrderBudgetRequestDto();
        requestDto.setOrderIds(orderIds);
        requestDto.setBeginTime(requestVo.getBeginTime());
        requestDto.setEndTime(requestVo.getEndTime());
        List<QueryOrderDetailResponse> flightPassData = orderClientLoader.getTrainPassData(requestDto);

        calculateBudget(flightPassData, corpBudgetInfoMap, orgInfoMap);
    }

    private void calculateiHotelBubgetAmount(List<GetOrderBillDateResponse> carBillDateResponses, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, GenBudgetRequestBO requestVo, Map<String, MbOrgInfo> orgInfoMap) {
        List<OrderBudgetRequestDto.OrderInfo> orderIds = carBillDateResponses.stream().map(response -> {
            return new OrderBudgetRequestDto.OrderInfo(response.getOrderId(), response.getRebookId(), response.getIsRefund() ? response.getOrderId() : null, response.getAmount());
        }).collect(Collectors.toList());
        OrderBudgetRequestDto requestDto = new OrderBudgetRequestDto();
        requestDto.setOrderIds(orderIds);
        requestDto.setBeginTime(requestVo.getBeginTime());
        requestDto.setEndTime(requestVo.getEndTime());
        List<QueryOrderDetailResponse> hotelPassData = orderClientLoader.getiHotelPassData(requestDto);

        calculateBudget(hotelPassData, corpBudgetInfoMap, orgInfoMap);
    }

    /**
    * author  Ks.Xing
    *
    * param hotelBillDateResponses
    * param corpBudgetInfoMap
    * param requestVo
    * param orgInfoMap
    * return  void
    * date 2023/3/23 14:54
    */

    private void calculateHotelBubgetAmount(List<GetOrderBillDateResponse> hotelBillDateResponses, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, GenBudgetRequestBO requestVo, Map<String, MbOrgInfo> orgInfoMap) {
        List<OrderBudgetRequestDto.OrderInfo> orderIds = hotelBillDateResponses.stream().map(response -> {
            return new OrderBudgetRequestDto.OrderInfo(response.getOrderId(), response.getRebookId(), response.getIsRefund() ? response.getOrderId() : null, response.getAmount());
        }).collect(Collectors.toList());
        OrderBudgetRequestDto requestDto = new OrderBudgetRequestDto();
        requestDto.setOrderIds(orderIds);
        requestDto.setBeginTime(requestVo.getBeginTime());
        requestDto.setEndTime(requestVo.getEndTime());
        List<QueryOrderDetailResponse> hotelPassData = orderClientLoader.getHotelPassData(requestDto);

        calculateBudget(hotelPassData, corpBudgetInfoMap, orgInfoMap);
    }

    /**
     * author  Ks.Xing
     *  计算国际机票产生的费用
     *  机票费用需要拆分到人程的维度
     * param flightBillDateResponses
     * param corpBudgetInfoMap
     * return  void
     * date 2023/3/21 16:45
     */
    private void calculateIntlFlightBubgetAmount(List<GetOrderBillDateResponse> intlFlightBillDateResponses, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, GenBudgetRequestBO requestVo, Map<String, MbOrgInfo> orgInfoMap) {
        List<OrderBudgetRequestDto.OrderInfo> orderIds = intlFlightBillDateResponses.stream().map(response -> {
            return new OrderBudgetRequestDto.OrderInfo(response.getOrderId(), response.getRebookId(), response.getRefundId(), response.getAmount());
        }).collect(Collectors.toList());
        OrderBudgetRequestDto requestDto = new OrderBudgetRequestDto();
        requestDto.setOrderIds(orderIds);
        requestDto.setBeginTime(requestVo.getBeginTime());
        requestDto.setEndTime(requestVo.getEndTime());
        List<QueryOrderDetailResponse> inflFlightPassData = orderClientLoader.getInflFlightPassData(requestDto);

        calculateBudget(inflFlightPassData, corpBudgetInfoMap, orgInfoMap);
    }

    /**
    * author  Ks.Xing
    *  计算国内机票产生的费用
    *  机票费用需要拆分到人程的维度
    * param flightBillDateResponses
    * param corpBudgetInfoMap
    * return  void
    * date 2023/3/21 16:45
    */
    private void calculateFlightBubgetAmount(List<GetOrderBillDateResponse> flightBillDateResponses, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, GenBudgetRequestBO requestVo, Map<String, MbOrgInfo> orgInfoMap) {

        List<OrderBudgetRequestDto.OrderInfo> orderIds = flightBillDateResponses.stream().map(response -> {
            return new OrderBudgetRequestDto.OrderInfo(response.getOrderId(), response.getRebookId(), response.getRefundId(), response.getAmount());
        }).collect(Collectors.toList());
        OrderBudgetRequestDto requestDto = new OrderBudgetRequestDto();
        requestDto.setOrderIds(orderIds);
        requestDto.setBeginTime(requestVo.getBeginTime());
        requestDto.setEndTime(requestVo.getEndTime());
        List<QueryOrderDetailResponse> flightPassData = orderClientLoader.getFlightPassData(requestDto);

        calculateBudget(flightPassData, corpBudgetInfoMap, orgInfoMap);
    }

    private void calculateBudget(List<QueryOrderDetailResponse> passData, Map<String, List<GetMbBudgetInfoResponse>> corpBudgetInfoMap, Map<String, MbOrgInfo> orgInfoMap) {
        passData.forEach(pass -> pass.setCorpId(getCorpIdByOrgId(orgInfoMap, pass.getOrgId())));
        Map<String, List<QueryOrderDetailResponse>> corpPassengerMap = passData.stream().filter(item -> Objects.nonNull(item.getCorpId())).collect(Collectors.groupingBy(QueryOrderDetailResponse::getCorpId));

        corpBudgetInfoMap.forEach((corpId, budgetInfo) -> {
            List<QueryOrderDetailResponse> responses = corpPassengerMap.get(corpId);
            if (CollectionUtils.isEmpty(responses)) {
                return;
            }

            budgetInfo.stream().forEach(budget -> {

                //按照部门维度匹配
                {
                    if (Objects.equals(BudgetScopeEnum.DEP.getType(), budget.getBudgetType())) {
                        List<QueryOrderDetailResponse> detailResponses = responses.stream().filter(detail -> budget.getScopeIds().contains(detail.getOrgId())).collect(Collectors.toList());
                        updateBudgetItemAmount(detailResponses, budget.getBudgetInfos(), BudgetTypeEnum.FLIGHT.getType(), budget.getId());
                    }
                }

                //按照项目维度匹配
                {
                    if (Objects.equals(BudgetScopeEnum.PRO.getType(), budget.getBudgetType())) {
                        List<QueryOrderDetailResponse> detailResponses = responses.stream().filter(detail -> StringUtils.isNotBlank(detail.getProjectId()) && budget.getScopeIds().contains(detail.getProjectId())).collect(Collectors.toList());
                        updateBudgetItemAmount(detailResponses, budget.getBudgetInfos(), BudgetTypeEnum.FLIGHT.getType(), budget.getId());
                    }
                }

                //按照成本中心维度匹配
                {
                    if (Objects.equals(BudgetScopeEnum.COS.getType(), budget.getBudgetType())) {
                        List<QueryOrderDetailResponse> detailResponses = responses.stream().filter(detail -> StringUtils.isNotBlank(detail.getCostCenterId()) && budget.getScopeIds().contains(detail.getCostCenterId())).collect(Collectors.toList());
                        updateBudgetItemAmount(detailResponses, budget.getBudgetInfos(), BudgetTypeEnum.FLIGHT.getType(), budget.getId());
                    }
                }

            });

        });

    }

    private void updateBudgetItemAmount(List<QueryOrderDetailResponse> detailResponses, List<GetMbBudgetInfoResponse.BudgetInfo> budgetInfos, String orderType, String budgetId) {
        if (CollectionUtils.isEmpty(detailResponses)) {
            return;
        }
        GetMbBudgetInfoResponse.BudgetInfo select = null;
        List<GetMbBudgetInfoResponse.BudgetInfo> budgetInfoList = budgetInfos.stream().filter(GetMbBudgetInfoResponse.BudgetInfo::getIsAll).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(budgetInfoList)) {
            select = budgetInfoList.get(0);
        } else {
            List<GetMbBudgetInfoResponse.BudgetInfo> budgetInfoLists = budgetInfos.stream().filter(b -> {
                if (Arrays.stream(b.getType().split("/")).anyMatch(type -> Objects.equals(type, orderType))) {
                    return Boolean.TRUE;
                }
                return Boolean.FALSE;
            }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(budgetInfoLists)) {
                select = budgetInfoLists.get(0);
            }
        }

        budgetInfoMapper.updateBudgetAmount(budgetId, detailResponses.stream().map(QueryOrderDetailResponse::getAmount).reduce(BigDecimal::add).get());
        if (Objects.nonNull(select)) {
            budgetItemMapper.updateBudgetAmount(select.getId(), detailResponses.stream().map(QueryOrderDetailResponse::getAmount).reduce(BigDecimal::add).get());
        }

    }

    /*public void updateAmount(String infoId, Long itemId, BigDecimal amount, String orgName, String type) {
        log.info("需要操作预算表数据: {}, {} ,{} ,{}", infoId, itemId, amount, orgName);


        //查询出预算数据计算  是否触发预算预警
        BudgetInfoEntity budgetInfoEntity = budgetInfoMapper.selectByPrimaryKey(infoId);
        List<BudgetNotifyEntity> budgetNotifyEntities = budgetNotifyMapper.selectByBudgetId(infoId);
        List<String> collect = budgetNotifyEntities.stream().map(BudgetNotifyEntity::getEmail).collect(Collectors.toList());

        if (budgetInfoEntity.getWarn().compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal divide = budgetInfoEntity.getWarn().divide(new BigDecimal("100"));
            BigDecimal multiply = budgetInfoEntity.getAmount().multiply(divide);
            if (budgetInfoEntity.getAmount().subtract(budgetInfoEntity.getAmountUsed()).compareTo(multiply) <= 0) {

                String contet = getContet("all", orgName, DateUtil.dateToString(budgetInfoEntity.getStartTime(), DateUtil.DF_YM_CN)
                        , DateUtil.dateToString(budgetInfoEntity.getEndTime(), DateUtil.DF_YM_CN), budgetInfoEntity.getAmount().toString()
                        , budgetInfoEntity.getAmount().subtract(budgetInfoEntity.getAmountUsed()).toString(), budgetInfoEntity.getWarn().toString() + "%");

                BudgetWarningEntity query = new BudgetWarningEntity();
                query.setBudgetId(budgetInfoEntity.getBudgetId());
                query.setBudgetType("all");
                List<BudgetWarningEntity> select = budgetWarningMapper.select(query);
                if (select.size() > 0) {
                    BudgetWarningEntity update = new BudgetWarningEntity();
                    update.setId(select.get(0).getId());
                    update.setContent(contet);
                    budgetWarningMapper.updateByPrimaryKey(update);
                } else {
                    BudgetWarningEntity entity = new BudgetWarningEntity();
                    entity.setBudgetId(budgetInfoEntity.getBudgetId());
                    entity.setBudgetType("all");
                    entity.setContent(contet);
                    entity.setEmall(StringUtils.join(collect, ","));
                    entity.setDatachangeCreatetime(new Date());
                    entity.setDatachangeLasttime(new Date());
                    entity.setIsDeleted(0);
                    budgetWarningMapper.insert(entity);
                }
            }
        }


        if (!Objects.isNull(itemId)) {

            BudgetItemEntity budgetItemEntity = budgetItemMapper.selectByPrimaryKey(itemId);

            if (budgetItemEntity.getWarn().compareTo(BigDecimal.ZERO) != 0 && !budgetItemEntity.getIsAll()) {
                BigDecimal divide = budgetItemEntity.getWarn().divide(new BigDecimal("100"));
                BigDecimal multiply = budgetItemEntity.getAmount().multiply(divide);
                if (budgetItemEntity.getAmount().subtract(budgetItemEntity.getAmountUsed()).compareTo(multiply) <= 0) {

                    String contet = getContet("sub", orgName, DateUtil.dateToString(budgetInfoEntity.getStartTime(), DateUtil.DF_YM_CN)
                            , DateUtil.dateToString(budgetInfoEntity.getEndTime(), DateUtil.DF_YM_CN), orderMap.get(type), budgetItemEntity.getAmount().toString()
                            , budgetItemEntity.getAmount().subtract(budgetItemEntity.getAmountUsed()).toString(), budgetItemEntity.getWarn().toString() + "%");


                    BudgetWarningEntity query = new BudgetWarningEntity();
                    query.setBudgetId(budgetInfoEntity.getBudgetId());
                    query.setBudgetType("sub");
                    query.setOrderType(type);
                    List<BudgetWarningEntity> select = budgetWarningMapper.select(query);
                    if (select.size() > 0) {
                        BudgetWarningEntity update = new BudgetWarningEntity();
                        update.setId(select.get(0).getId());
                        update.setContent(contet);
                        budgetWarningMapper.updateByPrimaryKey(update);
                    } else {
                        BudgetWarningEntity entity = new BudgetWarningEntity();
                        entity.setBudgetId(budgetItemEntity.getBudgetId());
                        entity.setBudgetType("sub");
                        entity.setContent(contet);
                        entity.setEmall(StringUtils.join(collect, ","));
                        entity.setOrderType(type);
                        entity.setDatachangeCreatetime(new Date());
                        entity.setDatachangeLasttime(new Date());
                        entity.setIsDeleted(0);
                        budgetWarningMapper.insert(entity);
                    }
                }
            }
        }
    }*/

    public String getCorpIdByOrgId (Map<String, MbOrgInfo> mbOrgInfos, String orgId) {
        MbOrgInfo mbOrgInfo = mbOrgInfos.get(orgId);
        if (Objects.isNull(mbOrgInfo)) {
            return null;
        }
        if (Objects.equals(OrgTypeEnum.C.getCode(), mbOrgInfo.getOrgType())) {
            return mbOrgInfo.getOrgId();
        }
        return getCorpIdByOrgId(mbOrgInfos, mbOrgInfo.getParentId());
    }

    public String getContet(String type,Object... org) {
        String all = "%s的%s-%s月的预算总金额额为¥%s，目前剩余预算金额为¥%s，已不足%s，请您及时关注。";
        String sub = "%s 的%s-%s的%s预算总金额额为¥%s，目前剩余预算金额为¥%s，已不足%s，请您及时关注。";
        if (Objects.equals("all", type)) {
            return String.format(all, org);
        } else {
            return String.format(sub, org);
        }
    }
}
